package com.asia5b.a5mall.middleware.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.asia5b.a5mall.middleware.utils.getEventBus
import com.asia5b.a5mall.middleware.utils.pop
import com.asia5b.a5mall.middleware.widget.refresh.AutoRefreshLayout
import com.jakewharton.rxbinding3.view.clicks
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import io.reactivex.disposables.CompositeDisposable
import java.util.concurrent.TimeUnit

/**
 * Created by zhangyuncai on 2020/8/19.
 */
abstract class SimpleFragment<VIEWMODEL : SimpleViewModel, DATABINDING : ViewDataBinding> : Fragment(), OnRefreshListener,
        OnLoadMoreListener, BaseControl {
    abstract val viewModelClazz: Class<VIEWMODEL>
    lateinit var mViewModel: VIEWMODEL
    lateinit var mDataBinding: DATABINDING
    val mCompositeDisposable = CompositeDisposable()
    open val isRegisterEventBus: Boolean = false//是否注册广播
    abstract fun getDataBinding(container: ViewGroup?): DATABINDING
    var mSmartRefreshLayout: AutoRefreshLayout? = null
        set(value) {
            field = value
            field?.setOnRefreshListener(this)
            field?.setOnLoadMoreListener(this)
        }
    protected val simpleLifecycleObserver by lazy { SimpleLifecycleObserver() }
    protected val mActivity: SimpleActivity<*, *> by lazy {
        requireActivity() as SimpleActivity<*, *>
    }

    lateinit var rootView: View

    var hasFetchData = false// 标识已经触发过懒加载数据

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel = ViewModelProvider(this).get(viewModelClazz)
        if (isRegisterEventBus) {
            if (!getEventBus().isRegistered(this)) {
                getEventBus().register(this)
            }
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (this::rootView.isInitialized) {
            if (rootView.parent != null && rootView.parent is ViewGroup) {
                (rootView.parent as ViewGroup).removeView(rootView)
            }
            return rootView
        }
        lifecycle.addObserver(simpleLifecycleObserver)
        mViewModel.loadingLiveData.observe(SimpleFragment@ this, Observer {
            when (it) {
                0 -> {
                    showLoadingBar("")
                }
                1 -> {
                    dismissLoadingBar()
                }
                else -> {
                    showLoadingFailureError()
                }
            }
        })
        mDataBinding = getDataBinding(container)
        rootView = mDataBinding.root
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (!hasFetchData) {
            initView()
            initEvent()
            startObserver()
        }
    }

    abstract fun initView()
    abstract fun initEvent()
    open fun startObserver() {}

    open fun eventBus() {

    }

    abstract fun lazyFetchData()

    fun showLoadingBar(content: String) {
        mActivity.showLoadingBar(content)
    }

    fun dismissLoadingBar() {
        mActivity.dismissLoadingBar()
        mSmartRefreshLayout?.finishRefresh()
        mSmartRefreshLayout?.finishLoadMore()
    }

    fun showLoadingFailureError(throwable: Throwable? = null) {
        mActivity.showLoadingFailureError(throwable)
        mSmartRefreshLayout?.finishRefresh()
        mSmartRefreshLayout?.finishLoadMore()
    }

    /**
     * 防止双击
     *
     * @param v
     */
    fun onFilterDoubleClick(v: View, listener: View.OnClickListener) {
        val subscribe = v.clicks()
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe { unit -> listener.onClick(v) }
        mCompositeDisposable.add(subscribe)
    }

    override fun onResume() {
        super.onResume()
        lazyFetchDataIfPrepared()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        lazyFetchDataIfPrepared()
    }

    private fun lazyFetchDataIfPrepared() {
        // 用户可见fragment && 没有加载过数据 && 视图已经准备完毕
        if ((this::rootView.isInitialized) && !hasFetchData && !isHidden) {
            hasFetchData = true
            lazyFetchData()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mCompositeDisposable.dispose()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isRegisterEventBus) {
            if (getEventBus().isRegistered(this)) {
                getEventBus().unregister(this)
            }
        }
        lifecycle.removeObserver(simpleLifecycleObserver)
        hasFetchData = false
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {

    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {

    }


    /**
     * @param  listener 监听回调
     */
    override fun addLifeCycleListener(listener: (state: Int) -> Unit) {
        simpleLifecycleObserver.add(listener)
    }

    fun pop() {
        (mActivity).pop()
    }

}